package com.shengyuan.manage_os.old.ying.erpm;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.json.JSONException;
import org.json.JSONObject;

import com.example.bluetoothprinter.BarcodeCreater;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.lvrenyang.pos.Cmd;
import com.lvrenyang.pos.Pos;
import com.shengyuan.manage_os.R;
import com.shengyuan.manage_os.myprinter.DrawerService;
import com.shengyuan.manage_os.myprinter.Global;
import com.shengyuan.manage_os.old.ying.erpm.controls.CurrentTime;
import com.shengyuan.manage_os.old.ying.erpm.db.Actual_Data_Table;
import com.shengyuan.manage_os.old.ying.erpm.util.Utility;
import com.shengyuan.manage_os.utils.EquipParam;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class Actual_Form_PrintFinished extends BasePrinterActivity {

	public static String Json1 , Json2, overtime;
	public static int RowId, mPrindCount;
	private static Handler mHandler = null;
	private static List<Map<String,String>> boundedPrinters;
	public static boolean PRINT_TEXT = false;

	private ProgressDialog mDialog;

	private ImageView barcode;
	private TextView editText_printecontent;
	private Bitmap mBitmap = null;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.actual_form_printfinished);
		editText_printecontent = (TextView) findViewById(R.id.editText_printecontent); 
		barcode = (ImageView) findViewById(R.id.image_barcode);
		startService(new Intent(Actual_Form_PrintFinished.this,DrawerService.class));
		mHandler = new MHandler(this);
		DrawerService.addHandler(mHandler);

		String text ="";
		String actual_form = getString(R.string.actual_form);
		String yusuanjiage = getString(R.string.title_actual_form_yusuanjiage);
		String cailiaojiage =  getString(R.string.title_actual_form_cailiaojiage);
		String jiage =  getString(R.string.title_actual_form_jiage);
		
		String video=getString(R.string.title_actual_form_VideoButton_Video);
		String voice = getString(R.string.title_actual_form_RecordButton_Record);
		String picture = getString(R.string.title_actual_form_PictureButton);
		String title1="", title = getString(R.string.actual_form_title);
		String jixieshiduan = getString(R.string.title_actual_form_edittext_jixieshiduan);
		try {
			System.out.println("#########+++++Json1===="+Json1);
			if(Json1==null){
				finish();
				return;
			}
			
			JSONObject json = new JSONObject(Json1);
			Iterator<String> it = json.keys();
			while (it.hasNext()) {
				String key = it.next().toString();
				if (!key.equals(voice) && !key.equals(video)
						&& !key.equals(actual_form) && !key.equals(title)
						&& !key.contains(yusuanjiage) &&  !key.contains(cailiaojiage)&&  !key.contains(jiage)) {
					if (key.contains(picture)) {
						//text += picture +  json.getString(key) + "\n";
					}else {
						text += key + json.optString(key) + "\n" ;
					}
				}
				if (key.equals(title)) {
					title1 = json.optString(key) + "\n";
				}
			}
			System.out.println("#########+++++Json2===="+Json2);
			if (Json2!=null && !Json2.equals("")) {
				text += "\n";
				json = new JSONObject(Json2);
				it = json.keys();
				while (it.hasNext()) {
					String key = it.next().toString();
					if (!key.equals(voice) && !key.equals(video)
							&& !key.equals(actual_form) && !key.equals(title)&& 
							!key.contains(yusuanjiage)&&  !key.contains(cailiaojiage) && !key.contains(jixieshiduan)&& !key.contains(jiage)) {
						if (key.contains(picture)) {
							//text += picture +  json.getString(key) + "\n";
						}else {
							text += key + json.getString(key) + "\n" ;
						}
					}
				}					
			}
			GenernalBarcode(overtime);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		text = title1 + text;
		editText_printecontent.setText(text);
		//Utility.HideEditFouce(editText_printecontent);
	}



	 class MHandler extends Handler {

		WeakReference<Actual_Form_PrintFinished> mActivity;

		public MHandler(Actual_Form_PrintFinished activity) {
			mActivity = new WeakReference<Actual_Form_PrintFinished>(activity);
		}

		@Override
		public void handleMessage(Message msg) {
			Actual_Form_PrintFinished theActivity = mActivity.get();
			switch (msg.what) {

				case Global.CMD_POS_SETBARCODERESULT: {
					int result = msg.arg1;
					if (result == 1){
						Actual_Form_PrintFinished.this.finish();
					}
					break;
				}

			}
		}
	}

	public Bitmap CreateOneDCode(String content) throws WriterException {
		// 生成一维条码,编码时指定大小,不要生成了图片以后再进行缩放,这样会模糊导致识别失败
		int w = EquipParam.getWindowWidth()*4/5;
		int h = w / 3;
		BitMatrix matrix = new MultiFormatWriter().encode(content,
				BarcodeFormat.CODE_128, w, h);
		int width = matrix.getWidth();
		int height = matrix.getHeight();
		int[] pixels = new int[width * height];
		for (int y = 0; y < height; y++) {
			for (int x = 0; x < width; x++) {
				if (matrix.get(x, y)) {
					pixels[y * width + x] = 0xff000000;
				}
			}
		}

		Bitmap bitmap = Bitmap.createBitmap(width, height,
				Bitmap.Config.ARGB_8888);
		// 通过像素数组生成bitmap,具体参考api
		bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
		return bitmap;
	}
	
	public void GenernalBarcode(String text) {

		try {
			mBitmap = CreateOneDCode(text);
		}catch (WriterException e){

		}
		barcode.setImageBitmap(mBitmap);
	}
	@Override
	protected void PrintingContent() {
		mPrindCount  = mPrindCount + 1;


		String message = editText_printecontent.getText().toString();
		if (message!=null && message.length()>0) {

			String text = "\n-----------------------------"+"\n";
			text += "日期:" + CurrentTime.getTimeString() + "\n";
			text += "制单人:" + LoginActivity.pmUser.UserName + "\n";
			text += "打印次数: " + mPrindCount + "\n";
			text += "内码ID: " + RowId + "\n";
			text += "条码: " + overtime+ "\n-----------------------------\n";


			String tilte = message.substring(0,message.indexOf("\n"));
			String cont = message.substring(message.indexOf("\n")+1,message.lastIndexOf("\n"));
			String content = tilte +"\n"+"-----------------------------"+"\n"+cont+"\n";
			message = content +"................................"+"\n\n";
			System.out.println("%%%%%%$$$$===="+tilte);
			System.out.println("%%%%%%$$$$message===="+text+message);
			if (DrawerService.workThread.isConnected()) {
				String titleName = getString(R.string.app_name)+"\n\n";
				Bundle dataCP = new Bundle();
				Bundle dataAlign = new Bundle();
				Bundle dataRightSpace = new Bundle();
				Bundle dataLineHeight = new Bundle();
				Bundle dataTextOut1 = new Bundle();
				dataCP.putInt(Global.INTPARA1, 15);
				dataCP.putInt(Global.INTPARA2, 255);
				dataAlign.putInt(Global.INTPARA1, 0);
				dataRightSpace.putInt(Global.INTPARA1, 0);
				dataLineHeight.putInt(Global.INTPARA1, 32);
				dataTextOut1.putString(Global.STRPARA1, titleName);
				dataTextOut1.putString(Global.STRPARA2, "GBK");
				dataTextOut1.putInt(Global.INTPARA1, 10);
				dataTextOut1.putInt(Global.INTPARA2, 1);
				dataTextOut1.putInt(Global.INTPARA3, 1);
				dataTextOut1.putInt(Global.INTPARA4, 0);
				dataTextOut1.putInt(Global.INTPARA5, 8);
				DrawerService.workThread.handleCmd(
						Global.CMD_POS_SETCHARSETANDCODEPAGE, dataCP);
				DrawerService.workThread.handleCmd(Global.CMD_POS_SALIGN,
						dataAlign);
				DrawerService.workThread.handleCmd(
						Global.CMD_POS_SETRIGHTSPACE, dataRightSpace);
				DrawerService.workThread.handleCmd(
						Global.CMD_POS_SETLINEHEIGHT, dataLineHeight);
				DrawerService.workThread.handleCmd(Global.CMD_POS_STEXTOUT,
						dataTextOut1);


				Bundle dataTextOut = new Bundle();
				dataTextOut.putString(Global.STRPARA1, text+message);
				dataTextOut.putString(Global.STRPARA2, "GBK");
				dataTextOut.putInt(Global.INTPARA1, 10);
				dataTextOut.putInt(Global.INTPARA2, 0);
				dataTextOut.putInt(Global.INTPARA3, 0);
				dataTextOut.putInt(Global.INTPARA4, 0);
				dataTextOut.putInt(Global.INTPARA5, 0);

				Bundle data = new Bundle();
				data.putString(Global.STRPARA1, overtime);
				data.putInt(Global.INTPARA1, 10);
				data.putInt(Global.INTPARA2, 73);
				data.putInt(Global.INTPARA3, 3);
				data.putInt(Global.INTPARA4, 96);
				data.putInt(Global.INTPARA5, 0);
				data.putInt(Global.INTPARA6, 2);
				DrawerService.workThread.handleCmd(Global.CMD_POS_SETBARCODE,
						data);

//				Actual_System_Setting.Instance.mBTService.PrintCharacters(text+message);

//				DrawerService.workThread.handleCmd(
//						Global.CMD_POS_SETCHARSETANDCODEPAGE, dataCP);
//				DrawerService.workThread.handleCmd(Global.CMD_POS_SALIGN,
//						dataAlign);
//				DrawerService.workThread.handleCmd(
//						Global.CMD_POS_SETRIGHTSPACE, dataRightSpace);
//				DrawerService.workThread.handleCmd(
//						Global.CMD_POS_SETLINEHEIGHT, dataLineHeight);
				DrawerService.workThread.handleCmd(Global.CMD_POS_STEXTOUT,
						dataTextOut);

			} else {
				boundedPrinters = getBoundedPrinters();
				String[] provinces = new String[boundedPrinters.size()];
				for(int i = 0; i < boundedPrinters.size(); i++){
					provinces[i] = boundedPrinters.get(i).get("name")+": "+boundedPrinters.get(i).get("addr");
				}

				AlertDialog dialog = new AlertDialog.Builder(this)
						.setTitle("请先连接打印机")
						.setItems(provinces,
								new DialogInterface.OnClickListener() {

									public void onClick(DialogInterface dialog1,
														int which) {
										mDialog = Utility.ShowModelDialog(Actual_Form_PrintFinished.this, "正在连接蓝牙...");
										String address = boundedPrinters.get(which).get("addr");
										DrawerService.workThread.connectBt(address,mDialog);
										mDialog.show();
									}
								}).create();

				dialog.show();
			}

		}
		
		Actual_Data_Table dbo = new Actual_Data_Table(this);
		dbo.Update_Data(RowId,Actual_Data_Table.PCOUNT, mPrindCount +"");
		dbo.close(); 
	}

	private List<Map<String,String>> getBoundedPrinters() {

		List<Map<String,String>> list = new ArrayList<Map<String,String>>();
		BluetoothAdapter mBluetoothAdapter = BluetoothAdapter
				.getDefaultAdapter();
		if (mBluetoothAdapter == null) {
			return list;
		}

		Set<BluetoothDevice> pairedDevices = mBluetoothAdapter
				.getBondedDevices();
		if (pairedDevices.size() > 0) {
			for (BluetoothDevice device : pairedDevices) {
				Map<String, String> map = new HashMap<String, String>();
				map.put("name", device.getName());
				map.put("addr", device.getAddress());
				list.add(map);
			}
		}
		return list;
	}
	  public void PrintImageOld(Bitmap bitmapCode)
	  {
	    int w = bitmapCode.getWidth();
	    int h = bitmapCode.getHeight();
	    byte[] sendbuf = StartBmpToPrintCode(bitmapCode);

	    int num = 0;
	    int total = 1152;

	    while (num != sendbuf.length)
	      if (true)
	      {
	        byte[] sendper;
	        if (sendbuf.length - num > total) {
	          sendper = new byte[total];
	          System.arraycopy(sendbuf, num, sendper, 0, total);
	          num += total;
	        } else {
	          sendper = new byte[sendbuf.length - num];
	          System.arraycopy(sendbuf, num, sendper, 0, sendbuf.length - 
	            num);
	          num = sendbuf.length;
	        }
	        try {
	          Thread.sleep(500);
	        }
	        catch (InterruptedException e) {
	          e.printStackTrace();
	        }
	        //write(sendper);
	        SettingActivity.sendBitMaptoPrinter(sendper);
	      }
	  }
	@Override
	protected void onDestroy() {
		super.onDestroy();
		DrawerService.delHandler(mHandler);
		mHandler = null;
	}


	@Override
	protected void onResume() {
		super.onResume();
	}

	@Override
	protected void Save_Send_Server() {
		Actual_Data_Table dbo = new Actual_Data_Table(this);
		dbo.Update_Data(RowId,Actual_Data_Table.SENDED, "1");
		dbo.close();
		setResult(RESULT_OK);
	}

	public static Bitmap resizeImage(Bitmap bitmap, int w, int h) {
		Bitmap BitmapOrg = bitmap;
		int width = BitmapOrg.getWidth();
		int height = BitmapOrg.getHeight();
		int newWidth = w;
		int newHeight = h;

		float scaleWidth = ((float) newWidth) / width;
		float scaleHeight = ((float) newHeight) / height;
		Matrix matrix = new Matrix();
		matrix.postScale(scaleWidth, scaleWidth);
		Bitmap resizedBitmap = Bitmap.createBitmap(BitmapOrg, 0, 0, width,
				height, matrix, true);
		return resizedBitmap;
	}
	  private byte[] StartBmpToPrintCode(Bitmap bitmap)
	  {
	    byte temp = 0;
	    int j = 7;
	    int start = 0;
	    if (bitmap != null) {
	      int mWidth = bitmap.getWidth();
	      int mHeight = bitmap.getHeight();

	      int[] mIntArray = new int[mWidth * mHeight];
	      byte[] data = new byte[mWidth * mHeight];
	      bitmap.getPixels(mIntArray, 0, mWidth, 0, 0, mWidth, mHeight);
	      encodeYUV420SP(data, mIntArray, mWidth, mHeight);
	      byte[] result = new byte[mWidth * mHeight / 8];
	      for (int i = 0; i < mWidth * mHeight; i++) {
	        temp = (byte)((byte)(data[i] << j) + temp);
	        j--;
	        if (j < 0) {
	          j = 7;
	        }
	        if (i % 8 == 7) {
	          result[(start++)] = temp;
	          temp = 0;
	        }
	      }
	      if (j != 7) {
	        result[(start++)] = temp;
	      }

	      int aHeight = 24 - mHeight % 24;
	      int perline = mWidth / 8;
	      byte[] add = new byte[aHeight * perline];
	      byte[] nresult = new byte[mWidth * mHeight / 8 + aHeight * perline];
	      System.arraycopy(result, 0, nresult, 0, result.length);
	      System.arraycopy(add, 0, nresult, result.length, add.length);

	      byte[] byteContent = new byte[(mWidth / 8 + 4) * (
	        mHeight + aHeight)];
	      byte[] bytehead = new byte[4];
	      bytehead[0] = 31;
	      bytehead[1] = 16;
	      bytehead[2] = (byte)(mWidth / 8);
	      bytehead[3] = 0;
	      for (int index = 0; index < mHeight + aHeight; index++) {
	        System.arraycopy(bytehead, 0, byteContent, index * (perline + 4), 4);
	        System.arraycopy(nresult, index * perline, byteContent, 
	          index * (perline + 4) + 4, perline);
	      }

	      return byteContent;
	    }
	    return null;
	  }
	  
	  public void encodeYUV420SP(byte[] yuv420sp, int[] rgba, int width, int height)
	  {
	    int frameSize = width * height;

	    int[] U = new int[frameSize];
	    int[] V = new int[frameSize];
	    int uvwidth = width / 2;

	    int bits = 8;
	    int index = 0;
	    int f = 0;
	    for (int j = 0; j < height; j++) {
	      for (int i = 0; i < width; i++) {
	        int r = (rgba[index] & 0xFF000000) >> 24;
	        int g = (rgba[index] & 0xFF0000) >> 16;
	        int b = (rgba[index] & 0xFF00) >> 8;

	        int y = (66 * r + 129 * g + 25 * b + 128 >> 8) + 16;
	        int u = (-38 * r - 74 * g + 112 * b + 128 >> 8) + 128;
	        int v = (112 * r - 94 * g - 18 * b + 128 >> 8) + 128;

	        byte temp = (byte)(y > 255 ? 255 : y < 0 ? 0 : y);
	        yuv420sp[(index++)] = (byte) (temp > 0 ? 1 : 0);
	      }
	    }
	    f = 0;
	  }
	  
	  
}
